﻿
using GameFramework.Event;
using GameFramework.ObjectPool;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.UIElements;
using UnityGameFramework.Runtime;

namespace LS.UI
{
    public abstract class LSUGuiForm : UIFormLogic
    {
        public const int DepthFactor = 100;
        private const float FadeTime = 0.3f;

        private static readonly Type s_SpriteType = typeof(Sprite);
        private object m_UserData;

        private Canvas m_CachedCanvas = null;
        private CanvasGroup m_CanvasGroup = null;
        private List<Canvas> m_CachedCanvasContainer = new List<Canvas>();
        public abstract bool FadeWithoutTimeScale { get; }

        public bool PauseCoveredUIForm
        {
            get; private set;
        }

        public bool AllowMultiInstance
        {
            get; private set;
        }

        public int OriginalDepth
        {
            get;
            private set;
        }

        public int Depth
        {
            get
            {
                return m_CachedCanvas.sortingOrder;
            }
        }

        public void Close()
        {
            Close(false);
        }

        public void Close(bool ignoreFade)
        {
            StopAllCoroutines();

            if (ignoreFade)
            {
                LSEntry.UI.CloseUIForm(this);
            }
            else
            {
                StartCoroutine(CloseCo(FadeTime));
            }
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnInit(object userData)
#else
        protected internal override void OnInit(object userData)
#endif
        {
            base.OnInit(userData);

            m_CachedCanvas = gameObject.GetOrAddComponent<Canvas>();
            m_CachedCanvas.overrideSorting = true;
            OriginalDepth = m_CachedCanvas.sortingOrder;
            
            m_CanvasGroup = gameObject.GetOrAddComponent<CanvasGroup>();

            RectTransform transform = GetComponent<RectTransform>();
            transform.anchorMin = Vector2.zero;
            transform.anchorMax = Vector2.one;
            transform.anchoredPosition = Vector2.zero;
            transform.sizeDelta = Vector2.zero;

            gameObject.GetOrAddComponent<GraphicRaycaster>();

            ReplayLanguage();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnRecycle()
#else
        protected internal override void OnRecycle()
#endif
        {
            base.OnRecycle();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnOpen(object userData)
#else
        protected internal override void OnOpen(object userData)
#endif
        {
            base.OnOpen(userData);

            UIFormParams par = userData as UIFormParams;
            this.m_UserData = par.UserData;
            this.AllowMultiInstance = par.AllowMultiInstance;
            this.PauseCoveredUIForm = par.PauseCoveredUIForm;

            m_CanvasGroup.alpha = 0f;
            StopAllCoroutines();
            StartCoroutine(m_CanvasGroup.FadeToAlpha(1f, FadeTime, FadeWithoutTimeScale));
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnClose(bool isShutdown, object userData)
#else
        protected internal override void OnClose(bool isShutdown, object userData)
#endif
        {
            m_UserData = null;
            AllowMultiInstance = default;
            PauseCoveredUIForm = default;

            base.OnClose(isShutdown, userData);
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnPause()
#else
        protected internal override void OnPause()
#endif
        {
            base.OnPause();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnResume()
#else
        protected internal override void OnResume()
#endif
        {
            base.OnResume();

            //ReplayLanguage();

            m_CanvasGroup.alpha = 0f;
            StopAllCoroutines();
            StartCoroutine(m_CanvasGroup.FadeToAlpha(1f, FadeTime));
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnCover()
#else
        protected internal override void OnCover()
#endif
        {
            base.OnCover();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnReveal()
#else
        protected internal override void OnReveal()
#endif
        {
            base.OnReveal();
            //ReplayLanguage();
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnRefocus(object userData)
#else
        protected internal override void OnRefocus(object userData)
#endif
        {
            base.OnRefocus(userData);
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnUpdate(float elapseSeconds, float realElapseSeconds)
#else
        protected internal override void OnUpdate(float elapseSeconds, float realElapseSeconds)
#endif
        {
            base.OnUpdate(elapseSeconds, realElapseSeconds);
        }

#if UNITY_2017_3_OR_NEWER
        protected override void OnDepthChanged(int uiGroupDepth, int depthInUIGroup)
#else
        protected internal override void OnDepthChanged(int uiGroupDepth, int depthInUIGroup)
#endif
        {
            int oldDepth = Depth;
            base.OnDepthChanged(uiGroupDepth, depthInUIGroup);
            int deltaDepth = UGuiGroupHelper.DepthFactor * uiGroupDepth + DepthFactor * depthInUIGroup - oldDepth + OriginalDepth;
            GetComponentsInChildren(true, m_CachedCanvasContainer);
            for (int i = 0; i < m_CachedCanvasContainer.Count; i++)
            {
                m_CachedCanvasContainer[i].sortingOrder += deltaDepth;
            }

            m_CachedCanvasContainer.Clear();
        }

        private IEnumerator CloseCo(float duration)
        {
            yield return m_CanvasGroup.FadeToAlpha(0f, duration);
            LSEntry.UI.CloseUIForm(this);
        }

        protected abstract void ReplayLanguage();

        public void LoadIcon(string path, Action<string, Sprite, float> loadSuccessCallback, Action<string, string> loadFaileCallBack = null)
        {
            var objectPoolCom = LSEntry.ObjectPool;
            var recourcesCom = LSEntry.Resource;
            if (LSEntry.ObjectPool.HasObjectPool<SpriteReferenceObject>())
            {
                IObjectPool<SpriteReferenceObject> pool = objectPoolCom.GetObjectPool<SpriteReferenceObject>();
                if (pool.CanSpawn(path))
                {
                    var usa = pool.Spawn(path);
                    loadSuccessCallback?.Invoke(path, usa.SpriteAsset, 0);
                    return;
                }
            }

            recourcesCom.LoadAsset(path, s_SpriteType, Constant.AssetPriority.UIIconAsset, new GameFramework.Resource.LoadAssetCallbacks(
                (assetName, asset, duration, userData) =>
                {
                    Sprite sprite = asset as Sprite;
                    IObjectPool<SpriteReferenceObject> pool;
                    if (sprite == null)
                    {
                        Texture2D txt = (Texture2D)asset;

                        if (objectPoolCom.HasObjectPool<SpriteReferenceObject>())
                        {
                            pool = objectPoolCom.GetObjectPool<SpriteReferenceObject>();
                        }
                        else
                        {
                            pool = objectPoolCom.CreateMultiSpawnObjectPool<SpriteReferenceObject>();
                        }

                        if (pool.CanSpawn(path))
                        {
                            sprite = pool.Spawn(path).SpriteAsset;
                        }
                        else
                        {
                            sprite = Sprite.Create(txt, new Rect(0, 0, (float)txt.width, (float)txt.height), Vector2.one * 0.5f);
                            pool.Register(SpriteReferenceObject.Create(path, sprite), true);
                        }
                    }
                    if (sprite != null)
                    {
                        loadSuccessCallback?.Invoke(assetName, sprite, duration);
                    }
                    else
                    {
                        loadFaileCallBack?.Invoke(assetName, $"Load icon: {path} is failed");
                    }
                },
                (assetName, status, errorMessage, userData) =>
                {
                    Log.Error("Can not load icon '{0}' from '{1}' with error message '{2}'.", path, assetName, errorMessage);
                    loadFaileCallBack?.Invoke(assetName, errorMessage);
                }));
        }

        public void UnspwonIcon(Sprite sprite)
        {
            var pool = LSEntry.ObjectPool.GetObjectPool<SpriteReferenceObject>();
            if (pool != null)
            {
                pool.Unspawn(sprite);
            }
        }
    }
}
